<?php

namespace app\common\logic;

use app\common\model\commonModel;
use app\common\model\trBusesLine;
use app\common\model\trCarList;
use app\common\model\trOrder;
use app\common\model\trOrderOutletsDetail;
use app\common\model\trOutletsCar;
use app\common\model\trSystemSet;
use app\common\model\trUser;
use app\common\util\Tools;
use think\Db;

/**
 * Class PayLogic
 * @package Common\Logic
 * 支付成功后的处理
 */
class PayLogic
{
    function update_pay_status($paymentId, $tradeData)
    {
        //Log::write("支付成功后返回的数据：" . var_export($tradeData, 1));
        $result = $this->updateOrder($paymentId, $tradeData);
        app()->db()->getConnection()->close(); // 关闭数据库连接
        return $result;
    }

    function updateOrder($paymentId, $tradeData)
    {
        try {
            $orderModel = new trOrder();
            $orderData = $orderModel->getFields("id,order_sn,line_id,user_id,contact_name,mobile,pay_money,type,reserve_time,address_from,address_to,ride_number,status,coupon_id,mall_id",
                ["payment_no" => $paymentId], true, false);
            if(empty($orderData)){
                Tools::writeLog("订单不存在", "PayLogic.txt");
                return false;
            }
            if ($orderData["status"] != "1") {
                Tools::writeLog("订单已支付", "PayLogic.txt");
                return true;
            }
            request()->mallData = ["id" => $orderData["mallId"]]; // 重置商城ID
            if(in_array($orderData["type"], [1,3])){ // 类型；1机场接送，2巴士路线，3跨境专车接送，4包车线路
                $updateData["status"] = 4;
            }else{
                $updateData["status"] = 2;
            }
            $updateData["pay_time"] = time();
            $updateData["update_time"] = time();
            $updateData["trade_no"] = $tradeData["tradeNo"];
            $updateData["pay_money"] = $tradeData["totalFee"];

            //更新订单状态
            if ($orderModel->doUpdate($updateData, ["payment_no" => $paymentId])) {
                if($orderData["type"] == "2"){ // 2巴士路线  需要把 延期余票 去掉
                    $model = new trBusesLine();
                    $reserveTime = explode(" ", $orderData["reserveTime"]);
                    $classesData = $model->getClassesCache($orderData["lineId"], $reserveTime[0]); // 班次数据
                    $classesData = Tools::array_replace($classesData, "shift");
                    if(isset($classesData[$reserveTime[1]]) && isset($classesData[$reserveTime[1]]["deferTicket"])) { // 有当前的班次
                        $classesData[$reserveTime[1]]["deferTicket"] = intval($classesData[$reserveTime[1]]["deferTicket"]) - intval($orderData["rideNumber"]);
                        $model->toSaveClassesCacheByOrder($orderData["lineId"], $reserveTime[0], array_values($classesData)); // 更新班次数据
                    }
                }elseif($orderData["type"] == "5"){ // 租车
                    $outletsData = trOrderOutletsDetail::alias("od")->leftJoin(trOutletsCar::getTable()." c", "c.id=od.oc_id")
                        ->where(["od.order_id" => $orderData["id"]])
                        ->field("od.id,od.oc_id,c.car_id,c.over_stock,c.id as outletsCarId")
                        ->find();
                    trOutletsCar::where("id", $outletsData->oc_id)->update(["over_stock" => $outletsData->over_stock - 1]);
                    $temp = trCarList::where(["car_id" => $outletsData->car_id, "attr_id" => $outletsData->outletsCarId, "type" => 5, "use" => 0])
                        ->field("plate_number,id")
                        ->find();
                    if(!empty($temp)) {
                        trOrderOutletsDetail::where("id", $outletsData->id)->update(["plate_number" => $temp->plate_number]);
                        trCarList::where("id", $temp->id)->update(["use" => 1]);
                    }
                }
                $orderData["typeName"] = $orderModel->getAttrByType($orderData["type"]);
                $orderData["mobilePrefix"] = substr($orderData["mobile"], 0, -11);
                $orderData["mobile"] = substr($orderData["mobile"], -11);
                SmsLogic::orderPay($orderData); // 发短信通知
                WxAppLogic::sendPayTpl($orderData["userId"], $tradeData["payAccount"], array_merge($orderData, Tools::transferFields($updateData)));
                $userModel = new trUser();//amount
                $userModel->doUpdate(["amount" => Db::raw("amount+{$tradeData["totalFee"]}")], ["id" => $orderData["userId"]]);
                // 已支付单通知提醒分配
                $orderLogic = new OrderLogic();
                if(in_array($orderData["type"], [1,3,4])) { // 1机场接送，2巴士路线，3专车接送，4包车线路
                    $orderLogic->toRemindOrder($orderData);
                }elseif($orderData["type"] == '2') {
                    $lineRemarkData = trSystemSet::getValue("enterpriseRemarks");
                    if (!empty($lineRemarkData["sendSmsStatus"])) { // 巴士路线提醒订单
                        $orderLogic->toRemindOrder($orderData);
                    }
                }
                // 修改优惠券状态
                if (!empty($orderData['couponId'])){
                    commonModel::toUpdate(userCouponTable, ["status" => 2, "order_id" => $orderData["id"]], ["id" => $orderData["couponId"]]);      // 已使用了
                }
            } else {
                Tools::writeLog("更新订单时候：订单状态更新失败", "PayLogic.txt");
                return false;
            }
        } catch (\Exception $e) {
            Tools::writeLog("支付回调过程出错：".$e->getMessage(), "orderPayResult.txt");
        }
        return true;
    }
}